#coding:utf-8

import time
import datamethod as dm
import report
import database
import dttime
from twisted.internet import reactor
import wx


class BaseProtocol(object):
    """Class Buss Data .Class Buss should not include other methods besides
    data analysing.Use Mixins to extend this buss if it is needed.
        
    data: @list or @string.
    """
    name = u""
    type = [0x00, 0x00]
    def __init__(self, data = ""):
        object.__init__(self)
        self.init()
        if data:
            self.setData(data)
            
    def init(self):
        pass
        
    def getList(self):
        """OverWrite this method."""
        return []
    
    def separate(self, data):
        pass
    
    def assemble(self, data):
        pass
   
    def setData(self, data):
        """Set Data of this instance."""
        data = dm.pickUps(data)
        self.separate(data)
        
    def getData(self):
        """Get list mode of data."""
        data = dm.pickUps(None)
        self.assemble(data)
        return data.out()
    
    def play(self):
        pass
    
    def parse(self):
        pass

    @classmethod
    def getType(cls):
        """Get busstype of this instance."""
        return cls.type
    
    @classmethod
    def getName(cls):
        """Get name of this instance."""
        return cls.name
    
    @classmethod
    def getTypeName(cls):
        return dm.data2str(cls.busstype)

class GpsProtocol(BaseProtocol):
    dtype = {u'压缩GPS数据1' : 0,
            u'压缩GPS数据2' : 1,
            u'标准GPS数据' : 2,
            u'差分GPS数据' : 3,
            u'其它' : 7}
                    
    dstate = {u'有效' : 0,
            u'无效' : 1}
    
    delec = {u'非省电' : 0,
            u'省电' :1}
                    
    dol = {u'空车' : 0,
            u'重车' :1}

    def init(self):
        self.datatype = 0x02
        self.time = [0x09, 0x01, 0x01, 0x00, 0x00, 0x00]
        self.gpsState = 0x00
        self.elec = 0x00
        self.overload = 0x00
        self.highdigit_lng = 0x00
        self.highdigit_speed = 0x00
        self.lat = [0x00] * 4
        self.lng = [0x00] * 4
        self.vector = [0x00]
        self.direction = [0x00]
    
    def separate(self, data):
        self.datatype = dm.pickUp(data.get(1)).get(5,7)
        self.time = data.get(6)
        p = dm.pickUp(data.get(1))
        self.gpsState = p.get(2, 2)
        self.elec = p.get(3, 3)
        self.overload = p.get(5, 5)
        self.highdigit_lng = p.get(6, 6)
        self.highdigit_speed = p.get(7, 7)
        self.lat = data.get(4)
        self.lng = data.get(4)
        self.vector = data.get(1)
        self.direction = data.get(1)
        
    def assemble(self, data):
        p = dm.pickUp()
        p.set(self.datatype, 5, 7)
        data.set(p.out(), self.time)
        p = dm.pickUp()
        p.set(self.gpsState, 2, 2)
        p.set(self.elec, 3, 3)
        p.set(self.overload, 5, 5)
        p.set(self.highdigit_lng, 6, 6)
        p.set(self.highdigit_speed, 7, 7)
        data.set(p.out(), self.lat, self.lng, self.vector, self.direction)
    
    def getElec(self):
        for i in self.delec.items():
            if i[1] == self.getValue(self.index+7, 3, 3):
                return i[0]
            
    def setElec(self, value):
        pass
        
    def getGpsState(self):
        pass
        
    def setGpsState(self, value):
        pass
        
    def getOverload(self):
        pass
        
    def setOverload(self, value):
        pass
        
    # GPS数据处理
    def _dealdata(self):
        # 7f转义
        for i in range(4, 16):
            if self.data[self.index+i] == 0x7f and i != 12:
                self.data[self.index+i] = 0
        # 经度和速度最高位转换
        for i in [12, 16]:
            if self.data[self.index+i] == 0xff:
                self.data[self.index+i] = 0
            elif self.data[self.index+i] == 0xfe:
                self.data[self.index+i] = 0x80
                
class BaseResource(object):
    @classmethod
    def getWants(cls):
        wants = {}
        for prop in dir(cls):
            if prop.startswith('p_'):
                wants[prop[2:]] = cls
        return wants
    
    def findFunc(self, busstype):
        if isinstance(busstype, list):
            busstype = "%02x%02x"%(busstype[0], busstype[1])
        busstype = busstype.replace(' ', '')
        if hasattr(self, 'p_%s'%busstype):
            return eval("self.p_%s"%busstype)

class BaseHunter(BaseResource):
    """BaseHunter. Parent class of all hunter."""
    name = "hunter"
    def __init__(self, workPlat):
        BaseResource.__init__(self)
        self.work = workPlat
        self.dataInfo = workPlat.currentInfo
        self.init()
        
    def init(self):
        pass
    
    def destroy(self):
        if hasattr(self, 'work'):
            del self.work
    
    def startWork(self, busstype, bussdata):
        func = self.findFunc(busstype)
        if func: return func(bussdata)
        
    def endWork(self):
        self.work.notifyWorkCompleted(self)

    def sendData(self, buss):
        busstype = buss.getType()
        bussdata = buss.getData()
        self.dataInfo.insertData(busstype, bussdata)
        self.work.sendData(busstype, bussdata)
        
    def recvData(self, busstype, bussdata):
        func = self.findFunc(busstype)
        if func:
            self.dataInfo.insertData(busstype, bussdata)
            return func(bussdata)
            
class BaseRender(BaseResource):
    def __init__(self, datas):
        BaseResource.__init__(self)
        self.datas = datas
        self.init()
        for data in self.datas:
           self.adapt(*data)
        
    def init(self):
        pass
    
    def show(self):
        pass
        
    def adapt(self, time, busstype, bussdata):
        self._restTime = time
        func = self.findFunc(busstype)
        if func:
            func(bussdata)
            return True
        else:
            return False
            
    def interprete(self, parent):
        self._parent = parent
        return self.show()
    
    def getTime(self):
        return self._restTime
           
    def getParent(self):
        if hasattr(self, '_parent'):
            return self._parent
    
    def buildWindow(self):
        pass



